/**
 * api调用接口的通用方法
 */

import axios from "axios"
import { PopupCommon } from "./popupCommon"
// 192.168.13.13 和 192.168.13.33 要打两个包后续只使用33

export const ImageAddress =
  window.location.origin.indexOf("192") != -1
    ? "http://192.168.13.33:9291"
    : "https://tcbim.cpolar.top"

/**
 * 文件服务器地址，环境不同，打包时替换下
 */
// export const fileAddress = "https://ccdc.linghangdzg.com"
export const fileAddress =
  window.location.origin.indexOf("192") != -1
    ? "http://192.168.13.33:9291"
    : "https://tcbim.cpolar.top"
// export const fileAddress = "http://42.192.50.79";

/**
 * 打印标签地址，环境不同，打包时替换下
 */
// export const printAddress = "https://ccdc.linghangdzg.com"
export const printAddress =
  window.location.origin.indexOf("192") != -1
    ? "http://192.168.13.33:9291"
    : "https://tcbim.cpolar.top"
/**
 * 请求接口的方法
 * @param {*} url
 * @param {*} type post/get
 * @param {*} data
 * @param {*} isFirst (特殊处理首次入住，periodNo设置为1)
 * @param {*} isNeedSave (是否不需要记录留痕)
 */
export const AjaxCommon = async (url, type, data, isFirst, isNeedSave) => {
  // let routeUrl = ""
  // routeJs 不需要，有个统一的js维护
  // const pathname = window.location.pathname.split("/")
  // routeUrl = pathname[pathname.length - 1]
  let jsonData = undefined
  if (type == "postForm") {
    let forms = new FormData()
    Object.keys(data).map((t) => {
      forms.append(t, data[t])
    })
    let headers = {
      token: localStorage.getItem("token"),
      Authorization: localStorage.getItem("token"),
    }
    jsonData = await axios
      .post(url, forms, {
        headers: headers,
      })
      .catch((res) => {
        console.log(res, "res......")
        gotoUrl(res.response?.data ?? res.response)
      })
    return jsonData
  } else if (type == "post") {
    let newData = JSON.parse(JSON.stringify(data))
    Object.keys(newData).map((t) => {
      newData[t] = encodeURIComponent(newData[t])
    })
    let headers = {
      token: localStorage.getItem("token"),
      Authorization: localStorage.getItem("token"),
      pageParam: JSON.stringify(newData),
    }
    if (isNeedSave) {
      delete headers.pageParam
      delete headers.routeUrl
      delete headers.routeJs
    }
    jsonData = await axios
      .post(url, data, {
        headers: headers,
      })
      .catch((res) => {
        gotoUrl(res.response.data)
      })
    return jsonData
  } else if (type == "postGet") {
    jsonData = await axios
      .post(url, {
        headers: {
          token: localStorage.getItem("token"),
          Authorization: localStorage.getItem("token"),
        },
      })
      .catch((res) => {
        gotoUrl(res.response.data)
      })
    return jsonData
  } else if (type == "get") {
    jsonData = await axios
      .get(url, {
        headers: {
          token: localStorage.getItem("token"),
          Authorization: localStorage.getItem("token"),
        },
      })
      .catch((res) => {
        gotoUrl(res.response.data)
      })
    return jsonData
  } else if (type == "getBlob") {
    jsonData = await axios
      .get(url, {
        headers: {
          token: localStorage.getItem("token"),
          Authorization: localStorage.getItem("token"),
        },
        responseType: "blob", // 设置响应类型为 blob
      })
      .catch((res) => {
        gotoUrl(res.response.data)
      })
    return jsonData
  } else if (type == "delete") {
    // let newUrl = ""
    // try {
    // 	newUrl = url.split("?")[1].split("=")[1]
    // } catch (error) {
    // 	console.log(error)
    // 	newUrl = ""
    // }
    // let newPageParam = data
    // newPageParam["id"] = newUrl
    // Object.keys(newPageParam).map((t) => {
    // 	newPageParam[t] = encodeURIComponent(newPageParam[t])
    // })
    jsonData = await axios
      .delete(url, {
        headers: {
          token: localStorage.getItem("token"),
          Authorization: localStorage.getItem("token"),
        },
      })
      .catch((res) => {
        gotoUrl(res.response.data)
      })
    return jsonData
  } else if (type == "deleteForm") {
    // let newUrl = ""
    // try {
    // 	newUrl = url.split("?")[1].split("=")[1]
    // } catch (error) {
    // 	console.log(error)
    // 	newUrl = ""
    // }
    // let newPageParam = data
    // newPageParam["id"] = newUrl
    // Object.keys(newPageParam).map((t) => {
    // 	newPageParam[t] = encodeURIComponent(newPageParam[t])
    // })
    jsonData = await axios
      .delete(url, {
        headers: {
          token: localStorage.getItem("token"),
          Authorization: localStorage.getItem("token"),
        },
        data: data,
      })
      .catch((res) => {
        gotoUrl(res.response.data)
      })
    return jsonData
  } else if (type == "put") {
    jsonData = await axios
      .put(url, data, {
        headers: {
          token: localStorage.getItem("token"),
          Authorization: localStorage.getItem("token"),
        },
      })
      .catch((res) => {
        gotoUrl(res.response.data)
      })
    return jsonData
  } else if (type == "putForm") {
    let forms = new FormData()
    Object.keys(data).map((t) => {
      forms.append(t, data[t])
    })
    let headers = {
      token: localStorage.getItem("token"),
      Authorization: localStorage.getItem("token"),
    }
    jsonData = await axios
      .put(url, forms, {
        headers: headers,
      })
      .catch((res) => {
        gotoUrl(res.response.data)
      })
    return jsonData
  }
}

const gotoUrl = (jsonData) => {
  if (jsonData?.code == 401 || jsonData?.status == 401) {
    PopupCommon.notify("error", jsonData.msg)
    setTimeout(() => {
      // window.location.href = "/zk-ui/userLogin"
      window.location.href = "/"
    }, 1500)
  } else if (jsonData?.code == 500 || jsonData?.status == 500) {
    PopupCommon.notify("error", jsonData.msg)
  } else {
    PopupCommon.notify("error", jsonData.msg)
  }
}
export const getProject = (url) => {
  return axios.get(url, {
    headers: {
      "X-Access-Token": localStorage.getItem("token"),
    },
  })
}

/**
 * 请求接口的方法（下载excel模板的方法）
 * @param {*} url
 */
export const AjaxCommonExcelDownload = async (url) => {
  let routeUrl = ""
  const pathname = window.location.pathname.split("/")
  routeUrl = pathname[pathname.length - 1]
  let projectTestperiod = window.sessionStorage.getItem("projectTestperiod")
  if (projectTestperiod) {
    projectTestperiod = JSON.parse(projectTestperiod)
  } else {
    if (
      localStorage.getItem("token") == "" ||
      localStorage.getItem("token") == null
    )
      // this.$router.replace({
      //   name: "userLogin",
      // })
      this.$router.replace({
        name: "/",
      })
  }
  return axios({
    url: url,
    method: "get",
    data: {},
    headers: {
      "X-Access-Token": localStorage.getItem("token"),
      pmId: projectTestperiod.projectId,
      expId: projectTestperiod.testId,
      periodNo: projectTestperiod.periodId,
      routeUrl: routeUrl,
      routeJs: "",
    },
    responseType: "blob",
  })
}
